package com.thinksns.sociax.t4.android.verify;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.thinksns.sociax.android.R;
import com.thinksns.sociax.api.ApiVerify;
import com.thinksns.sociax.component.CustomTitle;
import com.thinksns.sociax.component.LeftAndRightTitle;
import com.thinksns.sociax.constant.Verify;
import com.thinksns.sociax.t4.android.Thinksns;
import com.thinksns.sociax.t4.android.ThinksnsAbscractActivity;
import com.thinksns.sociax.t4.android.img.ActivityViewPager;
import com.thinksns.sociax.t4.android.popupwindow.PopUpWindowAlertDialog;
import com.thinksns.sociax.t4.android.video.ToastUtils;
import com.thinksns.sociax.t4.component.SmallDialog;
import com.thinksns.sociax.t4.model.ModelAttach;
import com.thinksns.sociax.t4.model.ModelBackMessage;
import com.thinksns.sociax.t4.model.ModelPhoto;
import com.thinksns.sociax.t4.model.ModelUser;
import com.thinksns.sociax.t4.model.VerifyDetails;
import com.thinksns.sociax.t4.unit.UnitSociax;
import com.thinksns.sociax.thinksnsbase.network.ApiHttpClient;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * @author LeiYan
 * @describe 认证详情
 * @date 2017/7/24
 * @contact email:907238552@qq.com
 */

public class VerifyDetailsActivity extends ThinksnsAbscractActivity {

    @BindView(R.id.tv_verify_state)
    TextView mTvVerifyState; // 认证状态
    // 认证类型
    @BindView(R.id.tv_verify_type)
    TextView mTvVerifyType;
    // 认证分类（二级）
    @BindView(R.id.ll_verify_classify)
    LinearLayout mLlVerifyClassify;
    @BindView(R.id.tv_verify_classify)
    TextView mTvVerifyClassify;
    @BindView(R.id.ll_organization_name)
    LinearLayout mLlOrganizationName;
    @BindView(R.id.tv_organization_name)
    TextView mTvOrganizationName;// 机构名称
    @BindView(R.id.tv_key_real_name)
    TextView mTvKeyRealName; // 真实姓名 or 负责人姓名 描述
    @BindView(R.id.tv_real_name)
    TextView mTvRealName; // 真实姓名 or 负责人姓名
    @BindView(R.id.tv_identity_id)
    TextView mTvIdentityId; // 身份证
    @BindView(R.id.tv_contact)
    TextView mTvContact; // 联系方式
    @BindView(R.id.tv_extra)
    TextView mTvExtra; // 补充资料
    //    @BindView(R.id.ll_identity_card_dec)
//    LinearLayout mLlAttachDefault;
    @BindView(R.id.ll_attach_container)
    LinearLayout mLlAttachContainer;
    @BindView(R.id.gv_attach)
    GridView mGvAttach;
    @BindView(R.id.btn_action)
    Button mBtnAction; // 重新提交 or 注销提交
    @BindView(R.id.tv_verify_attach_dec)
    TextView mTvAttachDec;
    private int mVerifyState; // 认证状态
    private VerifyDetails mVerifyDetails;
    private VerifyAttachAdapter mAttachAdapter;
    private SmallDialog mSmallDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
        getVerifyDetails();
    }

    private void init() {
        mSmallDialog = new SmallDialog(this, getString(R.string.please_wait));
        mSmallDialog.setCanceledOnTouchOutside(false);
        VerifyDetails verified = Thinksns.getMy().getVerified();
        if (verified != null) {
            if (Verify.TYPE_ORGANIZATION == verified.getUsergroup_id()) {
                mLlOrganizationName.setVisibility(View.VISIBLE);
                mTvKeyRealName.setText(R.string.key_manager_name);
                mTvAttachDec.setHint(R.string.hint_verify_attach_organization);
            } else {
                mLlOrganizationName.setVisibility(View.GONE);
                mTvKeyRealName.setText(R.string.key_real_name);
                mTvAttachDec.setHint(R.string.hint_verify_attach_other);
            }
            showVerifyState(verified.getVerified());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getVerifyDetails();
    }

    /**
     * 获取认证详情
     */
    private void getVerifyDetails() {
        mSmallDialog.show();
        ApiVerify.getInstance().getVerifyInfo(new ApiHttpClient.HttpResponseListener() {
            @Override
            public void onSuccess(Object result) {
                mSmallDialog.dismiss();
                VerifyDetails details = (VerifyDetails) result;
                showDetails(details);
            }

            @Override
            public void onError(Object result) {
                mSmallDialog.dismiss();
                ToastUtils.showToast(result == null ? getString(R.string.net_fail) : String.valueOf(result));
            }
        });
    }

    /**
     * 显示认证信息
     *
     * @param details
     */
    private void showDetails(VerifyDetails details) {
        if (details == null) return;
        mVerifyDetails = details;
        showVerifyState(details.getVerified()); // 认证状态
        mTvVerifyType.setText(details.getUser_group_name()); // 认证类型
        if (Verify.TYPE_ORGANIZATION == details.getUsergroup_id()) {
            mTvOrganizationName.setText(details.getUser_group_name());
            mTvKeyRealName.setText(R.string.key_manager_name);
            mTvAttachDec.setHint(R.string.hint_verify_attach_organization);
        } else {
            mLlOrganizationName.setVisibility(View.GONE);
            mTvKeyRealName.setText(R.string.key_real_name);
            mTvAttachDec.setHint(R.string.hint_verify_attach_other);
        }
        if (details.getUser_verified_category() != null) {
            mLlVerifyClassify.setVisibility(View.VISIBLE);
            mTvVerifyClassify.setText(details.getUser_verified_category().getTitle());
        } else {
            mLlVerifyClassify.setVisibility(View.GONE);
        }
        mTvRealName.setText(details.getRealname());
        mTvIdentityId.setText(details.getIdcard());
        mTvContact.setText(details.getPhone());
        /*字段更正， 8.15.2017*/
        if (!TextUtils.isEmpty(details.getReason())) {
            mTvExtra.setText(details.getReason());
        }
        // 附件
        if (details.getAttach_id() != null && !details.getAttach_id().isEmpty()) {
            mLlAttachContainer.setVisibility(View.VISIBLE);
            mTvAttachDec.setVisibility(View.GONE);
            mAttachAdapter = new VerifyAttachAdapter(this, mGvAttach, false, Verify.MAX_ATTACH_COUNT);
            mGvAttach.setAdapter(mAttachAdapter);
            mAttachAdapter.setData(details.getAttach_id());
        } else {
            mGvAttach.setVisibility(View.GONE);
            mTvAttachDec.setVisibility(View.VISIBLE);
        }
        mGvAttach.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                List<ModelAttach> data = mVerifyDetails.getAttach_id();
                List<ModelPhoto> photoList = new ArrayList<>();
                ModelPhoto photo = null;
                for (ModelAttach attach : data) {
                    photo = new ModelPhoto();
                    photo.setOriUrl(attach.getImage_url());
                    photoList.add(photo);
                }
                Intent intent = new Intent(view.getContext(), ActivityViewPager.class);
                intent.putExtra("index", position);
                intent.putParcelableArrayListExtra("photolist", (ArrayList<? extends Parcelable>) photoList);
                startActivity(intent);
            }
        });
    }

    /**
     * 认证状态 相关 view
     *
     * @param state
     */
    private void showVerifyState(int state) {
        mVerifyState = state;
        mBtnAction.setVisibility(View.VISIBLE);
        switch (state) {
            case Verify.STATE_REJECT:
                mTvVerifyState.setText(R.string.state_verify_reject);
                mBtnAction.setText(R.string.action_verify_re_commit);
                break;
            case Verify.STATE_VERIFIED:
                mTvVerifyState.setText(R.string.state_verify_pass);
                mBtnAction.setText(R.string.action_verify_cancel);
                break;
            case Verify.STATE_CHECKING:
                mTvVerifyState.setText(R.string.state_verify_checking);
                mBtnAction.setVisibility(View.GONE);
                break;
        }
    }


    /**
     * 注销认证
     */
    private void deleteVerify() {
        ApiVerify.getInstance().deleteVerify(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtils.showToast(R.string.net_fail);
            }

            @Override
            public void onResponse(String response, int id) {
                ModelBackMessage backMessage = new ModelBackMessage(response);
                ToastUtils.showToast(backMessage.getMsg());
                if (backMessage.isSuccess()) {
                    finish();
                }
            }
        });
    }

    /**
     * 重新提交认证信息
     */
    private void commitVerify() {
        if (mVerifyDetails == null) return;
        Intent intent = new Intent(this, DoVerifyHomeActivity.class);
        intent.putExtra("detail", mVerifyDetails);
        startActivity(intent);
        finish();
    }

    @OnClick({R.id.btn_action})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_action:
                if (Verify.STATE_REJECT == mVerifyState) {
                    commitVerify();
                } else if (Verify.STATE_VERIFIED == mVerifyState) {
                    showCancelWarnDialog();
                }
                break;
        }
    }

    private void showCancelWarnDialog() {
        PopUpWindowAlertDialog.Builder builder = new PopUpWindowAlertDialog.Builder(this);
        builder.setMessage(getString(R.string.warn_cancel_verify), 18);
        builder.setTitle(null, 0);
        builder.setPositiveButton(getString(R.string.action_ok), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                deleteVerify();
            }
        });

        builder.setNegativeButton(getString(R.string.action_cancel),
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        builder.create();
    }

    @Override
    public String getTitleCenter() {
        return getString(R.string.title_verify_home_verify);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_verify_details;
    }

    @Override
    protected CustomTitle setCustomTitle() {
        return new LeftAndRightTitle(R.drawable.img_back, this);
    }
}
